<?php

if (!session_id()) {
    session_start();
}
$user_id = $_SESSION['user_id'];

// get image detail 
if (isset($_POST['imgid']) && $_POST['imgid']) {
    global $wpdb;
    $current_img = $wpdb->get_row("SELECT * FROM ap_painting_img WHERE id = {$_POST['imgid']}");
    $imgs = explode("/", $current_img->url);
    $img_name = $imgs[count($imgs) - 1];

    //update image 
    $upload = wp_upload_dir();
    if (isset($_POST['imgBase64'])) {

        $img = str_replace('data:image/png;base64,', '', $_POST['imgBase64']);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $file = $upload['path'] . "/" . $img_name;
        $success = file_put_contents($file, $data);
        echo $upload['url'] . "/" . $img_name;
        ;
        die;
    }
} else {
    $upload = wp_upload_dir();
    if (isset($_POST['imgBase64'])) {
        $img_name = $user_id . "_" . time() . ".png";
        $img = str_replace('data:image/png;base64,', '', $_POST['imgBase64']);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $file = $upload['path'] . "/" . $img_name;
        $success = file_put_contents($file, $data);
    }

    global $wpdb;
    $tb = 'ap_painting_img';
    $imgurl = $upload['url'] . "/" . $img_name;
    $data = array('user_id' => $user_id, 'url' => $imgurl, 'dateadd' => time(),'layoutimg' => $_POST['layoutimg']);
    $wpdb->insert($tb, $data);

    echo $imgurl;
    die;
}
